from odoo import fields, models, _
from odoo.exceptions import UserError


class MrpMaterialReplacement(models.Model):
    _name = 's.mrp.material.replacement.wizard'
    _description = 'Material replacement'

    production_str = fields.Char(string='production str')
    line_ids = fields.One2many('s.mrp.material.replacement.line.wizard', 'order_id')

    def default_get(self, fields_list):
        result = super().default_get(fields_list)
        active_model = self._context.get('active_model', '')
        line_ids_vals = []
        if active_model == 'mrp.production':
            active_ids = self._context.get('active_ids', [])
            production_ids = self.env['mrp.production'].browse(active_ids).filtered(lambda x: x.state not in ('done', 'cancel'))
            result.update({'production_str': ','.join([str(i) for i in production_ids.ids])})
            move_raw_ids = production_ids.mapped('move_raw_ids').filtered(lambda x: x.state not in ('done', 'cancel'))
            product_ids = move_raw_ids.mapped('product_id').filtered(lambda x: x.categ_id.code not in ('BCP'))
            for product in product_ids:
                line_ids_vals.append((0, 0, {'product_id': product.id}))
        result['line_ids'] = line_ids_vals

        return result

    def action_confirm(self):
        p_list = self.production_str.split(',')
        production_ids = self.env['mrp.production'].browse([int(p) for p in p_list])
        count = 0
        for line in self.line_ids.filtered(lambda x: x.replace_product_id):
            if line.product_id.categ_id != line.replace_product_id.categ_id:
                raise UserError(_('Product : %s, Replace Product: %s, Different product categories',line.product_id.name,line.replace_product_id.name))
            move_raw_ids = production_ids.mapped('move_raw_ids').filtered(lambda x: x.state not in ('done', 'cancel'))
            need_replace_move_ids = move_raw_ids.filtered(lambda x: x.product_id == line.product_id)
            if need_replace_move_ids:
                need_replace_move_ids._do_unreserve()
                need_replace_move_ids.update({'product_id': line.replace_product_id.id})
                count += 1
            # 芯板发料单
            picking_ids = production_ids.mapped('s_material_picking_ids')
            need_replace_picking_move_ids = picking_ids.mapped('move_ids')\
                .filtered(lambda x: x.state not in ('done', 'cancel'))\
                .filtered(lambda x: x.product_id == line.product_id)
            if need_replace_picking_move_ids:
                need_replace_picking_move_ids._do_unreserve()
                need_replace_picking_move_ids.update({
                    'product_id': line.replace_product_id.id,
                    'description_picking': line.replace_product_id.name,
                    'name': line.replace_product_id.name,
                    'product_uom': line.replace_product_id.uom_id.id,
                })
                count += 1

        if count > 0:
            msg = _('Replacement successful')
        else:
            msg = _('No changes')
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'type': 'success',
                'message': msg,
                'next': {'type': 'ir.actions.act_window_close'},
            }
        }


class MrpMaterialReplacementLine(models.Model):
    _name = 's.mrp.material.replacement.line.wizard'
    _description = 'Material replacement Line'

    order_id = fields.Many2one('s.mrp.material.replacement.wizard')
    product_id = fields.Many2one('product.product', 'Product')
    replace_product_id = fields.Many2one('product.product', 'Replace Product')